<template>
  <page-view class="page-view" :title="false">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item><nuxt-link to="/meal/manage">餐券管理</nuxt-link></a-breadcrumb-item>
        <a-breadcrumb-item><nuxt-link to="meal/date">换餐管理</nuxt-link></a-breadcrumb-item>
        <a-breadcrumb-item>换餐通知</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card">
      <a-spin :spinning="sending">

        <!-- form -->
        <a-form :form="form" @submit="handleSubmit">
          <a-form-item label="通知标题" v-bind="formItemLayout">
            <a-input
              v-decorator="[
                'title',
                { rules: [{ required: true, message: '请输入通知标题' }] },
              ]"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="通知正文" v-bind="formItemLayout">
            <a-textarea
              v-decorator="[
                'content',
                { rules: [{ required: true, message: '请输入通知正文' }] },
              ]"
              :rows="4"
              placeholder="请输入"
              :style="{ resize: 'none' }"
              :autosize="{ minRows: 4, maxRows: 6 }"
            />
          </a-form-item>
          <span class="primary-link" @click="add">新增一行</span>
          <!-- form end -->

          <!-- table -->
          <a-table
            ref="table"
            bordered
            class="s-table"
            :row-key="_ => uuid()"
            :columns="columns"
            :scroll="{ y: scrollY }"
            :data-source="dateData"
            :pagination="false"
          >
            <template slot="scheduleDate" slot-scope="value,record,index">
              <a-date-picker
                :ref="value ? $moment(value).format('YYYY-MM-DD') : `date-picker-${index}`"
                :value="value ? $moment(value) : undefined"
                :disabled-date="getDisabledDates"
                @change="changeDate($event,record,index)"
              />
            </template>
            <span slot="breakfast" slot-scope="_, record" @change="onChange($event, record, '早餐')">
              <a-checkbox
                :class="[noChangeList.includes(record.scheduleDate) ? 'border-red' : '']"
                :checked="$get(record, 'typeNames', '').includes('早餐')"
                :disabled="!$get(scheduleMaps, `${record.scheduleDate}.typeNames`, '').includes('早餐')"
              />
            </span>
            <span slot="lunch" slot-scope="_, record" @change="onChange($event, record, '午餐')">
              <a-checkbox
                :class="[noChangeList.includes($get(record, 'scheduleDate')) ? 'border-red' : '']"
                :checked="$get(record, 'typeNames', '').includes('午餐')"
                :disabled="!$get(scheduleMaps, `${record.scheduleDate}.typeNames`, '').includes('午餐')"
              />
            </span>
            <span slot="dinner" slot-scope="_, record" @change="onChange($event, record, '晚餐')">
              <a-checkbox
                :class="[noChangeList.includes($get(record, 'scheduleDate')) ? 'border-red' : '']"
                :checked="$get(record, 'typeNames', '').includes('晚餐')"
                :disabled="!$get(scheduleMaps, `${record.scheduleDate}.typeNames`, '').includes('晚餐')"
              />
            </span>
            <template slot="action" slot-scope="text,record,index">
              <span class="danger-link" @click="del(text,record,index)">删除</span>
            </template>
          </a-table>
          <!-- table end -->

          <div class="footer-btn">
            <a-button :loading="sending" type="primary" html-type="submit">确定</a-button>
            <a-button @click="goback">取消</a-button>
          </div>
        </a-form>

      </a-spin>
    </a-card>

  </page-view>
</template>
<script>
import { mapState, mapActions } from 'vuex'
import { PageView, STable } from '@/components'
import { uuid } from '@/utils/util'

export default {
  name: 'Notice',
  components: { PageView, STable },
  inject: ['formItemLayout'],

  data () {
    return {
      scrollY: 400,
      sending: false,
      form: this.$form.createForm(this),
      columns: [
        { title: '订餐日期', align: 'center', dataIndex: 'scheduleDate', scopedSlots: { customRender: 'scheduleDate' }},
        { title: '早餐', width: '20%', align: 'center', dataIndex: 'breakfast', scopedSlots: { customRender: 'breakfast' }},
        { title: '午餐', width: '20%', align: 'center', dataIndex: 'lunch', scopedSlots: { customRender: 'lunch' }},
        { title: '晚餐', width: '20%', align: 'center', dataIndex: 'dinner', scopedSlots: { customRender: 'dinner' }},
        { title: '操作', width: '20%', align: 'center', scopedSlots: { customRender: 'action' }}
      ],
      dateData: [{ scheduleDate: '', typeNames: [] }],
      noChangeList: []
    }
  },

  computed: {
    ...mapState({
      mealTypeMaps: state => state.meal.mealTypeMaps,
      scheduleMaps: state => state.meal.scheduleMaps
    })
  },

  mounted () {
    if (!process.client) return false
    const viewHeight = document.querySelector('.ant-layout-content').offsetHeight
    this.scrollY = viewHeight - 64 - 55 - 24 - 48 - 64 - 164 - 20 - 55
    if (this.scrollY < 0) this.scrollY = 400
  },

  methods: {
    uuid,
    ...mapActions('meal', ['getSchedule']),

    getDisabledDates (d) {
      return this.dateData.map(({ scheduleDate }) => scheduleDate).includes(d.format('YYYY-MM-DD'))
    },

    goback () {
      this.$router.go(-1)
      setTimeout(this.$toggleSending, 300)
    },

    add () {
      const { dateData, $refs, $get } = this
      dateData.push({ scheduleDate: '', typeNames: [] })
      this.$nextTick(_ => {
        const dom = $get($refs, `date-picker-${dateData.length - 1}`, {})
        dom && dom.focus && dom.focus()
      })
    },

    del (value, item, index) {
      const { dateData } = this
      dateData.splice(index, 1)
    },

    async changeDate (date, item, index) {
      const { $moment, $get, getSchedule, dateData, $refs } = this
      const scheduleDate = date ? $moment(date).format('YYYY-MM-DD') : date
      this.$toggleSending(1)
      await getSchedule({ scheduleDate, refresh: false })
      Object.assign(item, { scheduleDate, typeNames: $get(this.scheduleMaps[scheduleDate], 'typeNames', '').split(',').filter(i => i) })
      dateData.sort((a, b) => $moment(a.scheduleDate || '9999-12-31').isBefore(b.scheduleDate || '9999-12-31') ? -1 : 1)
      this.$toggleSending()
      this.$nextTick(_ => {
        const dom = $get($refs, scheduleDate, {})
        dom && dom.focus && dom.focus()
      })
    },

    onChange (e, item, name) {
      const { noChangeList } = this
      if (!item.typeNames) Object.assign(item, { typeNames: [] })
      const { typeNames, scheduleDate } = item
      const index = typeNames.indexOf(name)
      if (index > -1) typeNames.splice(index, 1)
      else typeNames.push(name)
      if (scheduleDate && noChangeList.length) {
        const index = noChangeList.indexOf(scheduleDate)
        if (index > -1) noChangeList.splice(index, 1)
      }
    },

    handleSubmit (e) {
      const { dateData, scheduleMaps, $get, $message, changeMeal } = this
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          if (dateData.length) {
            const someDateEmpty = dateData.some(item => {
              const { scheduleDate, typeNames } = item
              if (!scheduleDate) {
                $message.error('请选择订餐日期')
                return true
              } else {
                const thisDate = scheduleMaps[scheduleDate]
                // 判断原来有没有数据，原来没有，且为空，则必须选择日期
                if (!thisDate && !$get(typeNames, 'length')) {
                  $message.error('请选择订餐类型')
                  return true
                }
              }
            })
            if (!someDateEmpty) changeMeal(values)
          }
        }
      })
    },

    async changeMeal ({ title = '', content = '' }) {
      const { noChangeList, dateData, scheduleMaps, $difference, $get, getDelData, getAddData, $axios, goback, $message } = this
      const deleteMealForm = []
      const addMealForm = []
      noChangeList.splice(0)
      dateData.some(item => {
        const { scheduleDate, typeNames } = item
        const old = scheduleMaps[scheduleDate] || {}
        const oldName = $get(old, 'typeNames', '').split(',')
        const addNames = $difference(typeNames, oldName).filter(i => i)
        const delNames = $difference(oldName, typeNames).filter(i => i)
        console.log(delNames)
        if (addNames.length) addMealForm.push(...getAddData(scheduleDate, addNames))
        if (delNames.length) deleteMealForm.push(...getDelData(old, delNames))
        if (!addNames.length && !delNames.length) return noChangeList.push(scheduleDate)
      })
      if (noChangeList.length) return $message.error('部分日期的订餐类型没有做出修改，请删除日期，或作出修改')
      const params = {
        addMealForm,
        deleteMealForm,
        messageForm: {
          content,
          title,
          status: 0,
          type: '换餐'
        }
      }
      this.$toggleSending(1)
      await $axios.post('api/mealChange/', params).then(res => {
        if (res.data.code === '000000') goback()
        else {
          $message.error($get(res, 'data.mesg', '请稍后再试'))
          this.$toggleSending()
        }
      }).catch(e => {
        $message.error('请稍后再试')
        this.$toggleSending()
      })
    },

    getDelData ({ ids = '', typeNames = '', scheduleDate }, names) {
      const { getAddData } = this
      const delIds = names.map(name => {
        const index = typeNames.split(',').indexOf(name)
        const id = ids.split(',')[index]
        return { ...getAddData(scheduleDate, [name])[0], id }
      })
      return delIds
    },

    getAddData (scheduleDate, names) {
      const { mealTypeMaps } = this
      const arr = names.map(name => {
        const { price, endTime, startTime, id } = mealTypeMaps.get(name)
        return { scheduleDate, price, endTime, startTime, typeId: id, name }
      })
      return arr
    }
  }
}
</script>
<style lang="less" scoped>
.s-card{
  .detail-item{
    .Flex;
    margin-bottom: 30px;
    span{
      font-weight: bold;
    }
    /deep/ .ant-checkbox-group-item{
      margin-left: 20px;
    }
  }
  .footer-btn{
    margin-top: 20px;
      .Flex;
      justify-content: center;
      .ant-btn{
          margin-right: 50px;
      }
  }
}

.danger-link {
  padding-left: 0;
}

.border-red {
  /deep/ .ant-checkbox-inner {
    border-color: @red;
    background: @red;
  }
}

</style>
